package logic

import (
	"baidu/models/cache"
	"baidu/models/mysql"
	"context"
	"fmt"

	"baidu/baidurpc/baidurpc"
	"baidu/baidurpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 登录
func (l *LoginLogic) Login(in *baidurpc.LoginRequest) (*baidurpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	get := cache.Rdb.Get(l.ctx, "sendSms"+in.Mobile)
	if get.Val() != in.SendCode {
		return nil, fmt.Errorf("短信验证码错误,请重新输入")
	}

	var findUser mysql.User
	mysql.DB.Debug().Where("account = ?", in.Account).Find(&findUser)

	if findUser.ID == 0 {
		return nil, fmt.Errorf("账号不存在,请前往注册")
	}

	if findUser.Password != in.Password {
		return nil, fmt.Errorf("密码错误,请重新输入")
	}

	return &baidurpc.LoginResponse{
		UserId: int64(findUser.ID),
	}, nil
}
